'use strict';

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Content = require('../models/content.model.js');
var Asset = require('../models/asset.model.js');

module.exports = router;


router.get('/contents', function (req, res, next) {

    Content.find(function (err, todos) {
        if (err) return next(err);
        res.json(todos);
    });
});

router.get('/contents/:id', function (req, res, next) {

    Content.findById(req.params.id, function (err, value) {
        if (err) return next(err);
        res.json(value);
    });
});

router.post('/contents', function (req, res) {

    Content.create(req.body, function (err, value) {
        if (err) return next(err);
        res.json(value);
    });

});

router.post('/contents/:id/media', function (req, res, next) {

    Content.findById(req.params.id, function (err, content) {
        if (err) return next(err);

        content.name = req.files['file'].originalname;

        var asset = new Asset({
            data: req.files['file'].buffer,
            contentType: req.files['file'].mimetype
        });

        asset.save(function () {

            content.asset = asset;

            content.save(function () {
                res.end();
            });
        });

    });
});


router.get('/assets/:id', function (req, res, next) {

    Asset.findById(req.params.id, function (err, asset) {

        if (err) return next(err);

        if (asset == null) {
            console.log('Asset not found');
            res.status(404).end();
            return;
        }

        res.set('Content-Type', asset.contentType);

        res.send(asset.data);
    });
});

router.delete('/contents/:id', function (req, res, next) {

    Content.findByIdAndRemove(req.params.id, req.body, function (err, content) {
        if (err) return next(err);

        Asset.findByIdAndRemove(content.asset, req.body, function (err, value) {
            if (err) return next(err);

            res.end();
        });
    });

});

router.put('/contents/:id', function (req, res, next) {

    delete req.body._id;


    Content.findByIdAndUpdate(req.params.id, req.body, function (err, value) {
        if (err) return next(err);
        res.json(value);
    });

});
